package kr.ac.kookmin.cs.keyboard;

import java.awt.BorderLayout;
import java.awt.Dimension;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;

import javax.swing.JButton;
import javax.swing.JComponent;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTextArea;
import javax.swing.JTextField;

public class CompleteDemo extends JPanel implements KeyListener, ActionListener {

	static int tickSum = 0;
	static boolean firstTouch = true;
	static boolean push_hang = false;
	static StringBuffer sb2 = new StringBuffer();
	static StringBuffer sb3 = new StringBuffer();
	JTextArea textArea;
	JTextField textFiled;
	static int previousNumber = 0;
	static int ii = 0;
	static int INTAVAL_MILLSEC = (int) (1000 / 14.4);
	static int REST_THRESHOLD = (int) (0.5 * 14.4);
	

	File outputFile;
	FileWriter fw;
	

	public static void main(String[] args) {


		javax.swing.SwingUtilities.invokeLater(new Runnable() {

			@Override
			public void run() {

				try {
					createAndShowGUI();
				} catch (IOException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}

			}

		});
		
	}

	public CompleteDemo() throws IOException {
		
		super(new BorderLayout());
		
		JButton jb = new JButton("Finish");
		
		jb.addActionListener(this);
		
		textFiled = new JTextField(20);
		
		textFiled.addKeyListener(this);
		
		// typingArea.setFocusTraversalKeysEnabled(false);
		
		textArea = new JTextArea();
		
		textArea.setEditable(false);
		
		textArea.setText("Finish 버튼 누르면 파일 생성됨");
		
		textFiled.setText("여기에 포커스두고 스페이스바 누르기 시작!");
		
		JScrollPane scrPanl = new JScrollPane(textArea);
		
		scrPanl.setPreferredSize(new Dimension(375, 125));
		
		add(textFiled, BorderLayout.PAGE_START);
		
		add(scrPanl, BorderLayout.CENTER);
		
		add(jb, BorderLayout.PAGE_END);
		
		
		
		do{
			
			outputFile = new File("./output" + ii++ + ".txt");
			//기존에 없던 파일이면 isFile()은 false
		}while(outputFile.isFile() == true);
		
		
		fw = new FileWriter(outputFile);
		
		fw.write("");
		
	}

	@Override
	public void keyPressed(KeyEvent event){
		
		
		if(firstTouch == true){
			System.out.println("first push");
			firstTouch = false;
			tickSum = 0;
		}
		
		if(push_hang == false){//누르고 있지 않을때, 첫번째 터치 이후부터
			
			if(firstTouch == false){
				if(tickSum >= REST_THRESHOLD){
					//System.out.println("쉬는 구간");
					sb2.append(previousNumber);
					sb2.append("\r\n");
					/*sb2.append(tickSum);//쉰 시간*/
					sb2.append("\r\n");
				}else if ( tickSum != 0){
					//System.out.println("저장됨");
					sb2.append("");
					sb2.append(previousNumber + tickSum);//쉰 시간
					sb2.append("\r\n");
				}
				
			}
			
			push_hang = true;
			tickSum = 0;
		}

	}

	@Override
	public void keyTyped(KeyEvent event) {
		
		//display(event, "KEY TYPED: ");
		
	}

	@Override
	public void keyReleased(KeyEvent event) {
		
		System.out.println("released!!");
		//display(event, "KEY RELEASED: ");
		push_hang = false;
		
		
		previousNumber = tickSum;
		
		
		//sb2.append(tickSum);
		//sb2.append("\r\n");
			
		display();
		
		tickSum = 0;

	}
	
	@Override
	public void actionPerformed(ActionEvent event) {//끝내기 버튼
		
		// Clear the text components.
		
		textArea.setText("./output" + (ii-1) + ".txt 에 저장됨");
		
		textFiled.setText("다시할려면 창 끄고 다시켜");
		
		sb2.append(previousNumber + "\r\n");
		
		//setVisible(false); //you can't see me!
		
		
		
		if(fw != null){
			
			try {
				
				fw.append(sb2.toString());
		
				fw.close();
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
			
		}
		
		// Return the focus to the typing area.
		
		textFiled.requestFocusInWindow();
		
		System.exit(0);
	}

	
	
	
	public void display(){
		
		textArea.setText("time gap : " + Integer.toString(tickSum));
		
	}
	

	private static void createAndShowGUI() throws IOException {

		// Make sure we have nice window decorations.

		JFrame.setDefaultLookAndFeelDecorated(true);

		// Create and set up the window.

		JFrame frame = new JFrame("KeyEventDemo");
		
		frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

		// Create and set up the content pane.

		JComponent newContentPane = new CompleteDemo();

		newContentPane.setOpaque(true); // content panes must be opaque

		frame.setContentPane(newContentPane);

		// Display the window.

		frame.pack();

		frame.setVisible(true);
		
		System.out.println("INTAVAL_MILLSEC : " + INTAVAL_MILLSEC);
		System.out.println("REST_THRESHOLD : " + REST_THRESHOLD);
		
		new Thread(){
			
			@Override
			public void run(){
				
				try {
					while(true){
						Thread.sleep(INTAVAL_MILLSEC);
						tickSum += 1;
					}
				} catch (InterruptedException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
				
			}
		}.start();

	}

}
